import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';

import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { InitService } from '../../../../public/serve/init/init.service';
import { Service } from '../../../../server/server';
import { PaginationComponent } from '../../../../public/pagination/pagination.component';
import { Router, ActivatedRoute,ParamMap } from '@angular/router';
import { appProjectUrl } from '../../project.url';
import { project } from '../../project.data';
declare var $: any;
@Component({
  selector: 'app-project-setting-add',
  templateUrl: './project-setting-add.component.html',
  styleUrls: ['./project-setting-add.component.css']
})
export class ProjectSettingAddComponent implements OnInit {

  treeData: TreeNode[];
  selectedFile: TreeNode[];
  taskId: string;
  searchData: any;

  selectedProduct: Array<object> = [];

  pageNo: number = 1;
  pageSize: number = 20;
  total: number = 0;
  naturalNum: number = 0;
  tabVal: Array<object>;

  isSelectAll: boolean = false;
  isChose: boolean = false;
  projectId :any = '';
  categoryId : any = '';

  @ViewChild('pagination') pagination: PaginationComponent;
  @Output() onSubmit = new EventEmitter<void>();

  constructor(
      public initService: InitService,
      private request: CudTableService,
      private hintsService: HintsService,
      public server: Service,
      private route:ActivatedRoute) { }

  isActive = this.server.isActive;
  ngOnInit() {
      this.server.eventEmit.subscribe((value: any) => {
          this.isActive = value;
      });
  }

  async getSettingProduct(projectId) {
      this.projectId = projectId;
      await this.getProductTypeTree();
      await this.toMogami();
  }

  /**
  * 树状图
  */
  async getProductTypeTree() {
      let url = this.server.baseUrl + 'service/producttype/getProductTypeTree?parentId=0';
      await this.request.getRequest(url).then((data: any) => {
          if (data.result_code == '0000') {
              this.treeData = data.result;
              //默认加载第一个
              //this.categoryId = data.result[0]['categoryId'];
              // 默认选中第一个节点（注释部分为：展开第一个节点）
              //this.selectedFile = [this.treeData[0]];
              // 展开所有节点
              this._expandAll();
              return
          } else {
              this.hintsService.messages(data.message, data.result_code);
          }
      }).catch();
  }

  /**
   * 展开所有树节点
   */
  _expandAll() {
      this.treeData.forEach(node => {
          this.expandRecursive(node, true);
      });
  }

  // 递归
  expandRecursive(node: TreeNode, isExpand: boolean) {
      node.expanded = isExpand;
      if (node.hasOwnProperty('childProductTypeVoList')) {
          node.children = node['childProductTypeVoList'];
          node.children.forEach(childNode => {
              this.expandRecursive(childNode, isExpand);
          });
      }
  }

  
  public treeTopActive:boolean = true;
  toMogami() {
    this.categoryId = '';
    this.getNoProjectProductList();
    this.treeTopActive = true;
  }

  // 选中某个树节点
  selectNode(event: any, type) {
    this.treeTopActive = false;
    this.categoryId = event.node[type];
    this.getNoProjectProductList();
  }

  

  /**
 * 主任务产品内容列表
 */
  async getNoProjectProductList() {
      this.isChose = this.isSelectAll = false;
      let data = this.getParams();
      await this.request.postRequest(this.server.baseUrl +appProjectUrl.getNoProjectProductList, data).then((res: any) => {
        if (res.result_code === '0000') {
              this.tabVal = res.result;
              this.total = res.length;
              this.naturalNum = project.pagination.naturalNum;
              this.isSelectAllInCurrent();
          } else {
              this.hintsService.messages(res.message, res.result_code);
          }
          return;
      }).catch((err: any) => {
          this.hintsService.messages("error", "error");
          return;
      });
  }

  //是否选中当前页所有数据
  isSelectAllInCurrent() {
      let index = 0;
      if (this.selectedProduct.length > 0 && this.tabVal.length > 0) {
          for (let item of this.selectedProduct) {
              for (let child of this.tabVal) {
                  if (item === child['productId']) {
                      child['checked'] = true;
                      index++;
                  }
              }
          }
          if (index === this.tabVal.length) {
              this.isChose = this.isSelectAll = true;
          }else {
              this.isChose = this.isSelectAll = false;
          }
      }
  }

  //产品内容列表查询参数
  private getParams() {
    return {
      token: project.retrieval.token,
      pageNo: this.pageNo,
      pageSize:this.pageSize,
      categoryId: this.categoryId,
      queryCriteria: this.searchData
    }
  }

  /**
   * 搜索
   */
  search() {
      this.getNoProjectProductList();
  }

  changesearch() {
      this.search();
  }

  /**
   * 分页
   * @param pagination 
   */
  _pagination(pagination: Array<any>) {
    project.pagination.pageNumber = pagination[0].pageNumber;
    project.pagination.pageSize = pagination[0].pageSize;
    project.pagination.naturalNum = (project.pagination.pageNumber - 1) * project.pagination.pageSize;
    this.getNoProjectProductList();
  }

  /**
   * 单选
   * @param bool
   * @param child
   * @param length
   */
  _chose(bool, child, length) {
      for (let item of this.tabVal) {
          if (item['productId'] === child) {
              item['checked'] = bool;
          }
      }

      if (bool) {
          this.selectedProduct.push(child);
      } else {
          var index = this.selectedProduct.indexOf(child);
          if (index > -1) {
              this.selectedProduct.splice(index, 1);
          }
      }
      this.isSelectAllInCurrent();
  }

  /**
   * 全选
   * @param bool
   * @param tabVal
   */
  _selectAll(bool, list) {
      for (let item of this.tabVal) {
          if (!bool) {
              item['checked'] = false;
              var index = this.selectedProduct.indexOf(item['productId']);
              if (index > -1) {
                  this.selectedProduct.splice(index, 1);
              }
          }

          if (bool) {
              item['checked'] = true;
              var index = this.selectedProduct.indexOf(item['productId']);
              if (index <= -1) {
                  this.selectedProduct.push(item['productId']);
              }
          }
      }
      this.isSelectAll = this.isChose = bool;
  }

  clearData() {
      this.isChose = this.isSelectAll = false;
      this.searchData = '';
      this.selectedProduct = [];
      this.pagination.currentPage = 1;
      this.pagination.pageSize = 20;
      project.pagination.pageNumber = 1;
      project.pagination.pageSize = 20;
      project.pagination.naturalNum = 0;
  }

  //设置产品的项目名称
  updateProductsProject() {
      let params = this.getUpdateProductsProjectParams();
      params.productIds = this.selectedProduct;
      this.request.postRequest(this.server.baseUrl + appProjectUrl.updateProductsProject, params).then((res: any) => {
          if (res.result_code === '0000') {
              this.onSubmit.emit();
          }
          this.hintsService.messages(res.message, res.result_code);

          return;
      }).catch((err: any) => {
          this.hintsService.messages("error", "error");
          return;
      });
      this.clearData();
      $("#settingProductAdd").modal('hide');
  }

  getUpdateProductsProjectParams() {
      return {
          token: project.retrieval.token,
          productIds: [],
          projectId: this.projectId
      }
  }

  //删除已选的产品
  _deleteSP(productId){
    this.selectedProduct.push(productId);
    this.projectId = '';
  }

  //删除已选的产品
  _deleteSettingProduct(){
    this.updateProductsProject();
  }
  
  

}
